/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controldepuntos.pantallas;

import controldepuntos.clases.AdministradorVentanas;
import controldepuntos.clases.TcReglamento;
import controldepuntos.clases.TrIncidente;
import controldepuntos.clases.Utilidades;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JOptionPane;

/**
 *
 * @author DIANA
 */
public class MAltaIncidencia extends javax.swing.JFrame {
    private static Integer idReglamento;
    ArrayList<TcReglamento> listaReglamento = new ArrayList<>();
    /**
     * Creates new form AltaIncidencias
     */
    public MAltaIncidencia() {
        initComponents();
        cargarCatalogoDeFaltas();
    }

    public void cargarCatalogoDeFaltas(){
        try{
            TcReglamento reglamento = new TcReglamento();
            listaReglamento = reglamento.seleccionarTodo();
            for(TcReglamento reglamentoActual : listaReglamento){
                cmbTipo.addItem(reglamentoActual.getDescripcion());
            }
            cmbTipo.setSelectedIndex(0);
        }catch(Exception ex){
            JOptionPane.showMessageDialog(this, ex.getMessage()+ex.getStackTrace(),"Error",JOptionPane.ERROR_MESSAGE);
        }
    }
    public Integer obtenerIdDeReglamentoSeleccionado(String elementoSeleccionado){
        try{
            Integer id=null;
            for(TcReglamento reglamentoActual : listaReglamento){
                if(reglamentoActual.getDescripcion()==elementoSeleccionado){
                    id=reglamentoActual.getIdReglamento();
                }
            }
            return id;
        }catch(Exception ex){
            return null;
        }
    }
    public boolean validarCampos(){
        try{
            boolean avanzar=true;
            String dia = String.valueOf(dtpFecha.getCalendar().get(Calendar.DAY_OF_MONTH));
            String mes = String.valueOf(dtpFecha.getCalendar().get(Calendar.MONTH)+1);
            String anio = String.valueOf(dtpFecha.getCalendar().get(Calendar.YEAR));
            if(mes.length()==1){
                mes="0"+mes;
            }
            if(dia.length()==1){
                dia="0"+dia;
            }
            String fechaCompleta = dia+"/"+mes+"/"+anio;
            DateFormat formato = DateFormat.getDateInstance(DateFormat.SHORT);
            if(formato.parse(fechaCompleta)==null){
                JOptionPane.showMessageDialog(this, "El campo Fecha no debe ir vacío y debe ser una fecha en formato dd/mm/yyyy. \n Por favor llene este campo","Error",JOptionPane.ERROR_MESSAGE);
                avanzar=false;
            }else{
                    if(cmbTipo.getSelectedIndex()==0){
                        JOptionPane.showMessageDialog(this, "El campo Tipo no debe ir vacío. \n Por favor llene este campo","Error",JOptionPane.ERROR_MESSAGE);
                        avanzar=false;
                    }
                
            }
            return avanzar;
        }
        catch(ParseException ex){
            JOptionPane.showMessageDialog(this, "El campo Fecha no debe ir vacío y debe ser una fecha en formato dd/mm/yyyy. \n Por favor llene este campo","Error: "+ex.getMessage(),JOptionPane.ERROR_MESSAGE);
            return false;
        }
        catch(Exception ex){
            JOptionPane.showMessageDialog(this, "Error al validar los campos. \n Por favor contrate al administrador del sistema","Error: "+ex.getMessage(),JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDetalles = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        cmbTipo = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        cmbHora = new javax.swing.JComboBox();
        cmbMinutos = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        dtpFecha = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(204, 204, 204));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Fecha:");
        jLabel1.setName("lblFecha"); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Hora:");
        jLabel2.setName("lblHora"); // NOI18N

        txtDetalles.setColumns(20);
        txtDetalles.setRows(5);
        txtDetalles.setName("txtDetalles"); // NOI18N
        txtDetalles.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDetallesKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDetallesKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(txtDetalles);

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Detalles:");
        jLabel3.setName("lblDetalles"); // NOI18N

        cmbTipo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cmbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Seleccione una opción--" }));
        cmbTipo.setName("cmbFaltas"); // NOI18N
        cmbTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTipoActionPerformed(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/controldepuntos/recursos/guardar.jpg"))); // NOI18N
        jButton1.setText("Guardar cambios");
        jButton1.setName("btnGuardar"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/controldepuntos/recursos/cancelar.jpg"))); // NOI18N
        jButton2.setText("Cancelar");
        jButton2.setName("btnCancelar"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/controldepuntos/recursos/LogoSIAPPSuperChico.jpg"))); // NOI18N

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel8.setText("Tipo:");

        cmbHora.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cmbHora.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }));

        cmbMinutos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cmbMinutos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }));

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Min:");

        dtpFecha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                dtpFechaKeyTyped(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel5.setText("Alta de incidencia");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(148, 148, 148)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel7)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(126, 126, 126)
                .addComponent(jButton1)
                .addGap(43, 43, 43)
                .addComponent(jButton2)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel8)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(cmbHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(17, 17, 17)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbMinutos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cmbTipo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(dtpFecha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel5))
                    .addComponent(jLabel7))
                .addGap(42, 42, 42)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(dtpFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmbHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(cmbMinutos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        AdministradorVentanas.mostrarPantallaModificarIncidencia();
        AdministradorVentanas.ocultarPantallaAltaIncidencia();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void cmbTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoActionPerformed
        
    }//GEN-LAST:event_cmbTipoActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try{
            if(validarCampos()){
                TrIncidente incidenteAInsertar = new TrIncidente();
                incidenteAInsertar.setIdAlumno(Utilidades.idAlumno);
                incidenteAInsertar.setIdReglamento(obtenerIdDeReglamentoSeleccionado(cmbTipo.getSelectedItem().toString()));
                String dia = String.valueOf(dtpFecha.getCalendar().get(Calendar.DAY_OF_MONTH));
                String mes = String.valueOf(dtpFecha.getCalendar().get(Calendar.MONTH)+1);
                String anio = String.valueOf(dtpFecha.getCalendar().get(Calendar.YEAR));
                if(mes.length()==1){
                    mes="0"+mes;
                }
                if(dia.length()==1){
                    dia="0"+dia;
                }
                String fechaCompleta = dia+"/"+mes+"/"+anio;
                //String fechaCompleta = anio+"-"+mes+"-"+dia;
                //JOptionPane.showMessageDialog(this, "Fecha actual: "+fechaCompleta);
                //DateFormat formato = DateFormat.getDateInstance(DateFormat.SHORT);
                DateFormat formato = DateFormat.getDateInstance(DateFormat.SHORT);
                //Se convierte. Si truena aquí significa que hay un error en la fecha
                formato.parse(fechaCompleta);
                //JOptionPane.showMessageDialog(this, "Fecha convertida: "+fecha);
                //DateFormat formato2 = DateFormat.getDateInstance(DateFormat.SHORT);
                incidenteAInsertar.setFecha(fechaCompleta);
                //JOptionPane.showMessageDialog(this, "Fecha asignada: "+incidenteAInsertar.getFecha());
                String hora = cmbHora.getSelectedItem().toString()+":"+cmbMinutos.getSelectedItem().toString()+":00";
                //JOptionPane.showMessageDialog(this, "Hora actual: "+hora);
                incidenteAInsertar.setHora(Time.valueOf(hora));
                incidenteAInsertar.setObservaciones(txtDetalles.getText());
                incidenteAInsertar.insertarIncidente(incidenteAInsertar);
            }
        }catch(Exception ex){
            JOptionPane.showMessageDialog(this, "Lo sentimos, ocurrió un error"+ex.getMessage()+ex.getStackTrace(),"Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void txtDetallesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDetallesKeyPressed
        
    }//GEN-LAST:event_txtDetallesKeyPressed

    private void dtpFechaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dtpFechaKeyTyped
        JOptionPane.showMessageDialog(rootPane, evt);
        //Utilidades.establecerLongitudMaxima(dtpFecha, evt, 0);
    }//GEN-LAST:event_dtpFechaKeyTyped

    private void txtDetallesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDetallesKeyTyped
        Utilidades.establecerLongitudMaxima(txtDetalles, evt, 500);
    }//GEN-LAST:event_txtDetallesKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MAltaIncidencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MAltaIncidencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MAltaIncidencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MAltaIncidencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MAltaIncidencia().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cmbHora;
    private javax.swing.JComboBox cmbMinutos;
    private javax.swing.JComboBox cmbTipo;
    private com.toedter.calendar.JDateChooser dtpFecha;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtDetalles;
    // End of variables declaration//GEN-END:variables
}
